<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j coupons page-coupons">
    <div class="content">
      <div class="coupon-banner">
        <img
          src="@/assets/images/coupon-center.jpg"
          alt
        >
      </div>
      <div
        v-if="dataList.length"
        class="coupons-con"
      >
        <div class="tit">
          <span class="bg-l" />{{ $t('coupons.generalCoupon') }}
          <span class="bg-r" />
        </div>
        <div class="con-box">
          <div
            v-for="(item, index) in dataList"
            :key="item.couponId"
            :class="['item', (item.canGoUse) ? 'received' : ((!item.stocks) ? 'robbed' : '')]"
          >
            <div class="text">
              <div class="coupon-price">
                <span
                  v-if="item.couponType === 1"
                  class="symbol"
                >￥</span>
                <span
                  v-if="item.couponType === 1"
                  class="big"
                >{{ item.reduceAmount }}</span>
                <span
                  v-if="item.couponType === 2"
                  class="big"
                >{{ item.couponDiscount }}</span>
                <span
                  v-if="item.couponType === 2"
                  class="symbol-s"
                >{{ $t('fold') }}</span>
                <span
                  v-if="$t('full')=='满'"
                  class="limit"
                >{{ $t('full') }}{{ $t('yuan') }}{{ item.cashCondition }}{{ $t('available') }}</span>
                <span
                  v-if="$t('full')!='满'"
                  class="limit"
                  style="maxWidth:110px"
                >{{ $t('available') }} {{ $t('over') }}{{ $t('yuan') }}{{ item.cashCondition }}</span>
              </div>
              <div
                v-if="item.suitableProdType === 0"
                class="range"
              >
                {{ $t('coupons.canUsedPurchaseFullRangeOfProducts') }}
              </div>
              <div
                v-if="item.suitableProdType !== 0"
                class="range"
              >
                {{ $t('coupons.onlySomeProductsOnThePlatformCanPurchased') }}
              </div>
              <div
                v-if="item.validTimeType === 1"
                class="time"
                style="line-clamp: 2"
              >
                {{ $t('coupons.validUntil') }}：{{ item.startTime }} - {{ item.endTime }}
              </div>
              <div
                v-if="item.validTimeType === 2"
                class="time"
                style="line-clamp: 2"
              >
                <span v-if="item.afterReceiveDays">
                  {{ $t('coupons.couponValidTips').replace('X', item.afterReceiveDays).replace('Y', item.validDays) }}
                </span>
                <span v-else>
                  {{ $t('coupons.onlyAfterCouponing') }} {{ item.validDays }} {{ $t('coupons.useWithinDays') }}
                </span>
              </div>
            </div>
            <div class="rest">
              <div
                class="number"
              >
                {{ item.stocks === 0?$t('coupons.soldOut'):$t('coupons.robbed')+parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%' }}
              </div>
              <div class="scale">
                <span
                  class="percent"
                  :style="{width:[item.stocks === 0?'100%' : ((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%']}"
                />
              </div>
              <a
                v-if="!item.canGoUse && item.stocks"
                href="javascript:void(0);"
                class="btn"
                @click="receiveCoupon(item,index,1)"
              >{{ $t('coupons.getItNow') }}</a>
              <a
                v-if="item.canGoUse"
                href="javascript:void(0);"
                class="btn"
                @click="useCoupon(item)"
              >{{ $t('coupons.goToUse') }}</a>
              <a
                v-if="!item.canGoUse && !item.stocks"
                href="javascript:void(0);"
                class="btn"
              >{{ $t('coupons.soldOut') }}</a>
            </div>
            <div
              v-if="item.canGoUse && $t('language') === 'zh_CN'"
              class="icon received-icon"
            />
            <div
              v-if="item.canGoUse && $t('language') !== 'zh_CN'"
              class="icon-en"
            >
              <img
                src="@/assets/images/coupon-received-en.png"
                alt=""
              >
            </div>
            <div
              v-if="!item.canGoUse && !item.stocks && $t('language') === 'zh_CN'"
              class="icon robbed-icon"
            />
            <div
              v-if="!item.canGoUse && !item.stocks && $t('language') !== 'zh_CN'"
              class="icon-en"
            >
              <img
                src="@/assets/images/coupon-robbed-en.png"
                alt=""
              >
            </div>
          </div>
        </div>
      </div>

      <div
        v-if="dataListProd && dataListProd.length"
        class="coupons-con"
      >
        <div class="tit">
          <span class="bg-l" />{{ $t('coupons.recommendedCoupons') }}
          <span class="bg-r" />
        </div>
        <div class="con-box">
          <div
            v-for="(item,index) in dataListProd"
            :key="item.couponId"
            :class="['s-item' , (item.canGoUse) ? 'received' : ((!item.stocks) ? 'robbed' : '') , (item.prods.length == 1) ? 'single': '']"
          >
            <!-- 多商品 -->
            <div
              v-if="item.prods.length > 1"
              class="goods-box"
            >
              <div class="shop-msg">
                <div class="logo">
                  <img-show :src="item.shopLogo" />
                </div>
                <div class="name">
                  {{ item.shopName }}
                </div>
              </div>
              <div class="prods">
                <div
                  v-for="(prod, prodIndex) in item.prods"
                  :key="prodIndex"
                  class="p-item"
                  @click="toProd(prod)"
                >
                  <div class="img">
                    <img-show :src="prod.pic" />
                  </div>
                  <div class="price">
                    ￥{{ prod.price }}
                  </div>
                </div>
              </div>
            </div>
            <div
              v-if="item.prods.length > 1"
              class="rest"
            >
              <div class="coupon-price">
                <span
                  v-if="item.couponType === 1"
                  class="symbol"
                >￥</span>
                <span
                  v-if="item.couponType === 1"
                  class="big"
                >{{ item.reduceAmount }}</span>
                <span
                  v-if="item.couponType === 2"
                  class="big"
                >{{ item.couponDiscount }}</span>
                <span
                  v-if="item.couponType === 2"
                  class="symbol-s"
                >{{ $t('fold') }}</span>
              </div>
              <div
                v-if="$t('full')=='满'"
                class="limit"
              >
                {{ $t('full') }}{{ $t('yuan') }}{{ item.cashCondition }}{{ $t('available') }}
              </div>
              <div
                v-if="$t('full')!='满'"
                class="limit"
                style="maxWidth:110px"
              >
                {{ $t('available') }} {{ $t('over') }}{{ $t('yuan') }}{{ item.cashCondition }}
              </div>
              <div class="scale">
                <div
                  class="number"
                >
                  {{ item.stocks === 0?$t('coupons.soldOut'):$t('coupons.robbed') + parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%' }}
                </div>
                <div
                  class="percent"
                  :style="{width:[item.stocks === 0?'100%' : parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%']}"
                />
              </div>
              <a
                v-if="!item.canGoUse && item.stocks"
                href="javascript:void(0);"
                class="btn"
                @click="receiveCoupon(item,index,2)"
              >{{ $t('coupons.getItNow') }}</a>
              <a
                v-if="item.canGoUse"
                href="javascript:void(0);"
                class="btn"
                @click="useCoupon(item)"
              >{{ $t('coupons.goToUse') }}</a>
              <a
                v-if="!item.canGoUse && !item.stocks"
                href="javascript:void(0);"
                class="btn"
              >{{ $t('coupons.soldOut') }}</a>
            </div>
            <!-- /多商品 -->
            <!-- 单商品 -->
            <div
              v-if="item.prods.length == 1"
              class="single-box"
            >
              <div class="img">
                <img-show :src="item.prods[0].pic" />
              </div>
              <div class="text-box">
                <div class="goods-name">
                  {{ item.prods[0].prodName }}
                </div>
                <div class="scale-box">
                  <div
                    class="number"
                  >
                    {{ item.stocks === 0?$t('coupons.soldOut'):$t('coupons.robbed') + parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%' }}
                  </div>
                  <div class="scale">
                    <div
                      class="percent"
                      :style="{width:[item.stocks === 0?'100%' : parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%']}"
                    />
                  </div>
                </div>
                <div class="coupon-info">
                  <div class="coupon-price">
                    <span
                      v-if="item.couponType === 1"
                      class="symbol"
                    >￥</span>
                    <span
                      v-if="item.couponType === 1"
                      class="big"
                    >{{ item.reduceAmount }}</span>
                    <span
                      v-if="item.couponType === 2"
                      class="big"
                    >{{ item.couponDiscount }}</span>
                    <span
                      v-if="item.couponType === 2"
                      class="symbol-s"
                    >{{ $t('fold') }}</span>
                    <div
                      v-if="$t('full')=='满'"
                      class="limit"
                    >
                      {{ $t('full') }}{{ $t('yuan') }}{{ item.cashCondition }}{{ $t('available') }}
                    </div>
                    <div
                      v-if="$t('full')!='满'"
                      class="limit"
                      style="maxWidth:110px"
                    >
                      {{ $t('available') }} {{ $t('over') }}{{ $t('yuan') }}{{ item.cashCondition }}
                    </div>
                  </div>
                  <a
                    v-if="!item.canGoUse && item.stocks"
                    href="javascript:void(0);"
                    class="btn"
                    @click="receiveCoupon(item,index,2)"
                  >{{ $t('coupons.getItNow') }}</a>
                  <a
                    v-if="item.canGoUse"
                    href="javascript:void(0);"
                    class="btn"
                    @click="useCoupon(item)"
                  >{{ $t('coupons.useNow') }}</a>
                  <a
                    v-if="!item.canGoUse && !item.stocks"
                    href="javascript:void(0);"
                    class="btn"
                  >{{ $t('coupons.soldOut') }}</a>
                </div>
              </div>
            </div>
            <!-- /单商品 -->
            <div
              v-if="item.canGoUse && $t('language') === 'zh_CN'"
              class="icon received-icon"
            />
            <div
              v-if="item.canGoUse && $t('language') !== 'zh_CN'"
              class="icon-en"
            >
              <img
                src="@/assets/images/coupon-received-en.png"
                alt=""
              >
            </div>
            <div
              v-if="!item.canGoUse && !item.stocks"
              class="icon robbed-icon"
            />
            <div
              v-if="!item.canGoUse && !item.stocks && $t('language') !== 'zh_CN'"
              class="icon-en"
            >
              <img
                src="@/assets/images/coupon-robbed-en.png"
                alt=""
              >
            </div>
          </div>
        </div>
      </div>
      <pagination
        v-model="current"
        :pages="pages"
        @change-page="getProdCouponList"
      />
      <!-- 商品列表为空 -->
      <empty-all-tips
        v-if="isEmpty && ((!dataList.length && !dataListProd.length) || (!dataList && !dataListProd))"
        :text="$t('coupons.sorryNoCouponsAvailable')"
        :back="$t('backToHome')"
        :src-type="3"
      />
      <!-- /商品列表为空 -->
    </div>
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

onMounted(() => {
  document.title = $t('userCenter.couponCenter')
  getGeneralCouponList()
  getProdCouponList(1)
})

// 到商品详情页
const toProd = (prod) => {
  const newPage = router.resolve({ path: '/detail', query: { prodId: prod.prodId } })
  window.open(newPage.href, '_blank', 'noopener,noreferrer')
}

const dataList = ref([]) // 通用券列表
/**
* 获取通用券列表
*/
const getGeneralCouponList = () => {
  const url = Cookie.get('bbcToken') ? '/p/myCoupon/generalCouponList' : '/coupon/generalCouponList'
  http.get(url).then(({ data }) => {
    initCouponCanGoUseFlag(data)
    dataList.value = data
    console.log('🚀 ~ http.get ~ data:', data)
  })
}

const isEmpty = ref(false)
const current = ref(route.query.current || 1) // 当前页数
const dataListProd = ref([]) // 商品券列表
const pages = ref(0) // 总页数
/**
 * 获取商品券列表
 */
const getProdCouponList = () => {
  isEmpty.value = false
  const url = Cookie.get('bbcToken') ? '/p/myCoupon/getCouponPage' : '/coupon/getCouponPage'
  http.get(url, {
    params: {
      current: current.value,
      size: 20
    }
  }).then(({ data }) => {
    initCouponCanGoUseFlag(data.records)
    dataListProd.value = data.records
    isEmpty.value = true
    pages.value = data.pages
  })
}

/**
 * 初始化优惠券去可以使用的标记
 */
const initCouponCanGoUseFlag = (couponList) => {
  couponList.forEach(coupon => {
    coupon.canGoUse = coupon.curUserReceiveCount >= coupon.limitNum
  })
}

/**
 * 设置优惠券可以去使用的标记
 */
const setCouponCanGoUseFlag = (index, couponType) => {
  if (couponType === 1) {
    const tempCouponList = dataList.value
    tempCouponList[index].canGoUse = true
    tempCouponList[index].stocks -= 1
    dataList.value = tempCouponList
  } else if (couponType === 2) {
    const tempCouponList = dataListProd.value
    tempCouponList[index].canGoUse = true
    tempCouponList[index].stocks -= 1
    dataListProd.value = tempCouponList
  }
}

/**
* 领取优惠券
*/
const receiveCoupon = (item, index, coupontype) => {
  if (item.couponId) {
    http.post('/p/myCoupon/receive', item.couponId).then(({ data }) => {
      if (data) {
        ElMessage({
          message: data,
          type: 'success',
          duration: 1500
        })
      }
      setCouponCanGoUseFlag(index, coupontype)
    })
  }
}

/**
 * 立即使用
 */
const useCoupon = (item) => {
  let url = {
    path: '/list',
    query: {
      st: 4
    }
  }
  const couponId = item.couponId
  const prodList = item.prods
  if (prodList && prodList.length === 1) {
    const newPage = router.resolve({ path: '/detail', query: { prodId: prodList[0].prodId } })
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  } else {
    if (item.shopId) {
      // 店铺主页
      url = {
        path: '/shop-index',
        query: {
          sid: item.shopId
        }
      }
    } else if (couponId) {
      // 商品列表
      url = {
        path: '/list',
        query: {
          st: 4,
          couponId
        }
      }
    }
    router.push(url)
  }
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
